package ReentrantReadWriteLock_4;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class OrderedResource {
    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(true); // 公平模式

    public void readResource() {
        rwLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始读取资源");
            Thread.sleep(30); // 模拟读取时间
            System.out.println(Thread.currentThread().getName() + " 完成读取");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void writeResource() {
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 开始写入资源");
            Thread.sleep(50); // 模拟写入时间
            System.out.println(Thread.currentThread().getName() + " 完成写入");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }
}

public class 公平模式读写锁_资源访问顺序 {
    public static void main(String[] args) {
        final OrderedResource resource = new OrderedResource();

        // 创建20个读取线程
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {
                public void run() {
                    resource.readResource();
                }
            }, "读取线程-" + i).start();
        }

        // 创建5个写入线程
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                public void run() {
                    resource.writeResource();
                }
            }, "写入线程-" + i).start();
        }
    }
}
